/*
 * Copyright (c) 2014 - 2017. Company.Domain Co.Ltd. All rights reserved.
 */

package cn.com.dhc.danlu.business.favorite.adapter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.goods.GoodInfoActivity;
import cn.com.dhc.danlu.dlware.OperatorUtils;
import cn.com.dhc.danlu.dlware.net.GeneralBusinessObserver;
import cn.com.dhc.danlu.util.CommonConst;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.adapter.BaseRecyclerviewAdapter;
import cn.com.hd.mall.web.webservices.entity.BaseResponse;
import cn.com.hd.mall.web.webservices.entity.request.mydl.favorite.DelFavoriteRequest;
import cn.com.hd.mall.web.webservices.entity.response.mydl.favorite.FavoriteListResponse;

import static cn.com.dhc.danlu.dlware.global.DanluApplication.agent;

/**
 * @Author: nieqigang@danlu.com
 * @Date: 2017.3.28
 */
public class FavoriteListAdapter extends BaseRecyclerviewAdapter<FavoriteListAdapter.MyViewHolder> {
    private Context mContext;
    private LayoutInflater mInflater;
    private SparseBooleanArray mCheckStates = new SparseBooleanArray();
    private boolean mIsEditMode = false;

    public FavoriteListAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
        mContext = context;
    }

    @Override
    public void onBindViewHolder(final FavoriteListAdapter.MyViewHolder holder, int position) {
        final FavoriteListResponse.FavoriteMerchModel model =
                (FavoriteListResponse.FavoriteMerchModel) getDatas().get(position);
        // 商品状态
        final String status = model.getMerchStatus();

        holder.itemView.setTag(position);
        holder.itemView.setOnClickListener(new FavoriteItemClick(holder, status, model));
        holder.itemView.setBackgroundResource(R.color.ui_bg);

        holder.mGoodsPhoto.setImageURI(model.getPicUrl());
        //货物名字
        holder.mGoodsName.setText(model.getMerchName());
        holder.mSellerName.setText(model.getSellerName());

        String price = "￥" + CommonUtils.fenToYuan(new BigDecimal(model.getUnitPrice())).toPlainString();
        holder.mGoodsPrice.setText(price);

        holder.propagandaTips.setText(model.getPropagandaInfo());
        setGoodsStatus(holder, status);

        setCheckBoxStatus(holder, position);
    }

    @Override
    public FavoriteListAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new MyViewHolder(mInflater.inflate(R.layout.dl_item_favorite, parent, false));
    }

    private void setGoodsStatus(final FavoriteListAdapter.MyViewHolder holder, String status) {
        if (CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_0.equals(status)) {
            holder.mGoodsStatus.setVisibility(View.GONE);
            return;
        }

        holder.mGoodsStatus.setVisibility(View.VISIBLE);
        switch (status) {
            //缺货
            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_1:
                holder.mGoodsStatus.setText(R.string.shopping_cart_goods_quehuo);
                break;
            //已下架
            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_2:
                holder.mGoodsStatus.setText(R.string.shopping_cart_goods_yixiajia);
                break;
            //已失效
            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_3:
                holder.mGoodsStatus.setText(R.string.shopping_cart_goods_yishixiao);
                break;
            //商品不存在
            case CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_4:
                holder.mGoodsStatus.setText(R.string.shopping_cart_goods_noexist);
                break;
            default:
                break;
        }
    }

    private void setCheckBoxStatus(final FavoriteListAdapter.MyViewHolder holder, int position) {
        if (mIsEditMode) {
            holder.mCheckBox.setVisibility(View.VISIBLE);
            holder.mCheckBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int pos = (Integer) holder.itemView.getTag();
                    if (holder.mCheckBox.isSelected()) {
                        mCheckStates.delete(pos);
                        holder.mCheckBox.setSelected(false);
                    } else {
                        mCheckStates.put(pos, true);
                        holder.mCheckBox.setSelected(true);
                    }
                }
            });
            holder.mCheckBox.setSelected(mCheckStates.get(position, false));
        } else {
            holder.mCheckBox.setVisibility(View.INVISIBLE);
        }
    }

    public boolean isAtLeastOneChecked() {
        return mCheckStates.size() > 0;
    }

    public void deleteSelectedItem() {
        ArrayList<String> merchIds = new ArrayList<>();
        ArrayList<Integer> deletePostions = new ArrayList<>();
        for (int i = 0; i < mCheckStates.size(); ++i) {
            int pos = mCheckStates.keyAt(i);
            if (mCheckStates.valueAt(i)) {
                merchIds.add(((FavoriteListResponse.FavoriteMerchModel)
                        getDatas().get(pos)).getMerchId());
                deletePostions.add(pos);
            }
        }

        if (merchIds.size() <= 0) {
            return;
        }

        delFavoriteOnServer(merchIds, deletePostions);
    }

    private void delFavoriteOnServer(ArrayList<String> merchIds, final ArrayList<Integer> deletePostions) {
        DelFavoriteRequest delFavoriteRequest = new DelFavoriteRequest();
        // 设置token
        delFavoriteRequest.setToken(agent.getToken());
        // 设置商品id
        delFavoriteRequest.setMerchId(merchIds);
        // 删除收藏
        agent.getApi().delFavourite(delFavoriteRequest).compose(OperatorUtils.defaultSchedulers())
                .subscribe(new GeneralBusinessObserver<BaseResponse>(mContext, R.string.tips_del) {
                    @Override
                    protected void onSuccess(BaseResponse baseResponse) {
                        //删除成功后从视图上删除被勾选Item
                        Collections.sort(deletePostions);
                        for (int k = deletePostions.size() - 1; k >= 0; k--) {
                            int pos = deletePostions.get(k);
                            getDatas().remove(pos);
                        }
                        mCheckStates.clear();
                        notifyDataSetChanged();
                        // 刷新数据
                        ToastUtil.getInstance().show(R.string.good_info_del_shop_suceed_prompt);
                    }

                    @Override
                    protected void onAlertTips(String displayMessage) {
                        ToastUtil.getInstance().show(displayMessage);
                    }

                    @Override
                    protected String parseBussinessException(String code) {
                        return mContext.getString(R.string.good_info_del_shop_failed_prompt);
                    }
                });

    }

    public void setEditMode(boolean isEditMode) {
        mIsEditMode = isEditMode;
        notifyDataSetChanged();
    }

    public boolean isCurrentInEditMode() {
        return mIsEditMode;
    }

    class MyViewHolder extends RecyclerView.ViewHolder {
        private ImageView mCheckBox;
        private SimpleDraweeView mGoodsPhoto;
        private TextView mGoodsName;
        private TextView mGoodsPrice;
        private TextView mGoodsStatus;
        private TextView mSellerName;
        private TextView propagandaTips;

        public MyViewHolder(View view) {
            super(view);
            mCheckBox = (ImageView) view.findViewById(R.id.checkbox);
            mGoodsPhoto = (SimpleDraweeView) view.findViewById(R.id.goods_photo);
            mGoodsName = (TextView) view.findViewById(R.id.goods_name);
            mGoodsPrice = (TextView) view.findViewById(R.id.goods_price);
            mGoodsStatus = (TextView) view.findViewById(R.id.goods_status);
            mSellerName = (TextView) view.findViewById(R.id.seller_name);
            propagandaTips = (TextView) view.findViewById(R.id.propaganda_tips);
        }
    }

    private class FavoriteItemClick implements View.OnClickListener {
        private MyViewHolder mHolder;
        private String mStatus;
        private FavoriteListResponse.FavoriteMerchModel mModel;

        public FavoriteItemClick(MyViewHolder holder, String status,
                                 FavoriteListResponse.FavoriteMerchModel model) {
            mHolder = holder;
            mStatus = status;
            mModel = model;
        }

        @Override
        public void onClick(View v) {
            if (mIsEditMode) {
                int pos = (Integer) mHolder.itemView.getTag();
                boolean isChecked = mCheckStates.get(pos, false);
                mHolder.mCheckBox.setSelected(!isChecked);
                if (mHolder.mCheckBox.isSelected()) {
                    mCheckStates.put(pos, true);
                } else {
                    mCheckStates.delete(pos);
                }
            } else if (CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_0.equals(mStatus)
                    || CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_1.equals(mStatus)) {
                Bundle bundle = new Bundle();
                bundle.putString(CommonConst.IntentKey.MERCHANDISE_ID, mModel.getMerchId());
                Intent intent = new Intent(mContext, GoodInfoActivity.class);
                intent.putExtras(bundle);
                mContext.startActivity(intent);
            } else if (CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_2.equals(mStatus)) {
                // 商品已下架
                ToastUtil.getInstance().show(R.string.good_undercarriage);
            } else if (CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_3.equals(mStatus)) {
                // 商品已失效
                ToastUtil.getInstance().show(R.string.good_losed);
            } else if (CommonConst.ShoppingCarModel.GOODS_STATUS_FLG_4.equals(mStatus)) {
                // 商品不存在
                ToastUtil.getInstance().show(R.string.good_unexist);
            }
        }
    }
}
